<?php

class FileExt extends CApplicationComponent
{
    protected $path, $model;
    private $__image;
    public $imageClass;

    public function init()
    {
        $this->path=Yii::app()->basePath.'/../'.Yii::app()->params['uploadImagePath'];
        $this->model=new File();

        Yii::import('ext.fileExt.classes.*');
        $nameParts=explode('.',$this->imageClass['class']);
        $imageClass=end($nameParts);
        $this->__image=new $imageClass($this->imageClass['thumbs']);
    }

    public function getModel()
    {
        return $this->model;
    }

    public function getImage()
    {
        return $this->__image;
    }

    public function saveImage($model,$imageName)
    {
        $image=CUploadedFile::getInstance($model,$imageName);
        if($image===null) return false;

        $name=time().'-'.$image->name;

        if($image->saveAs($this->path.$name)){
            $this->model->name=$name;
            $this->model->fileName=$name;
            $this->model->type='img';
            $this->model->source=$this->path.$name;

            $this->model->save();

            if($error=$this->model->getErrors()){
                Yii::app()->notification=$error;
                return false;
            }

            return $this->model->id;
        }else{
            if($error=$image->getError()) Yii::app()->notification=$error;
            return false;
        }
    }

    public function getImageUrl($id=0)
    {
        return $this->image->getImageUrl($id);
    }

    public function getDownloadLink($htmlOptions=array())
    {
        return CHtml::link($this->model->name, array('admin/file/download', 'id'=>$this->model->id), $htmlOptions);
    }
}